package com.bocloud.cmp.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.bocloud.cmp.dao.DictionaryDao;
import com.bocloud.cmp.entity.Dictionary;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.BasicDao;

/**
 * 字典操作数据层接口实现类
 * 
 * @author dmw
 *
 */
@Component("dictionaryDao")
public class DictionaryDaoImpl extends BasicDao implements DictionaryDao {

	@Override
	public List<Dictionary> list(String value) throws Exception {
		List<Object> list = new ArrayList<>();
		if (StringUtils.hasText(value)) {
			String sql = "select * from dictionary where pvalue = :value";
			Map<String, Object> params = MapTools.simpleMap(Common.VALUE, value);
			list = this.queryForList(sql, params, Dictionary.class);
		} else {
			String sql = "select * from dictionary where pvalue = '0'";
			list = this.queryForList(sql, Dictionary.class);
		}
		List<Dictionary> dicts = new ArrayList<>();
		for (Object obj : list) {
			Dictionary dict = (Dictionary) obj;
			dicts.add(dict);
		}
		return dicts;
	}

	@Override
	public List<Dictionary> list() throws Exception {
		List<Object> objects = this.queryForList("SELECT * FROM dictionary ", Dictionary.class);
		List<Dictionary> dictionaries = new ArrayList<>();
		if (null != objects) {
			for (Object obj : objects) {
				dictionaries.add((Dictionary) obj);
			}
		}
		return dictionaries;
	}

	@Override
	public List<Object> listChildren(String value) throws Exception {
		if (StringUtils.hasText(value)) {
			String sql = "SELECT * FROM dictionary a WHERE a.pvalue = :value";
			List<Object> objects = this.queryForList(sql, MapTools.simpleMap("value", value), Dictionary.class);
			return objects;
		} else {
			String sql = "SELECT * FROM dictionary a WHERE a.pvalue='0'";
			List<Object> objects = this.queryForList(sql, null, Dictionary.class);
			return objects;
		}
	}

	@Override
	public Dictionary getRegionByID(Long id) throws Exception {
		Dictionary dic = (Dictionary) this.loadEntity(Dictionary.class, id);
		return dic;
	}

	@Override
	public Dictionary query(Long id) throws Exception {
		String sql = "select * from dictionary where id = :id";
		Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
		List<Object> list = this.queryForList(sql, param, Dictionary.class);
		if (list.isEmpty()) {
			return null;
		}
		return (Dictionary) list.get(0);
	}
}
